package net.hound.site.video;

import net.cl.support.json.JsonArray;
import net.cl.support.json.JsonObject;
import net.cl.utils.HttpUtil;
import net.cl.utils.StringUtil;
import net.hound.IHound;

/**
 * http://tv.sohu.com/20110417/n305949099.shtml
 * 
 * @author caol64@gmail.com
 * 
 */
public class Sohu implements IHound {

	private static final String INDEX_PREFIX = "http://hot.vrs.sohu.com/vrs_flash.action?vid=";
	private String url;
	private static final String encoding = "UTF-8";

	public Sohu(String url) {
		this.url = url;
	}

	@Override
	public String getSource(String userAgent) {
		String html = HttpUtil.getResponseString(url, encoding);
		String vid = StringUtil.getMatch("var vid=\"(\\d{1,})\";", html);
		if (vid == null)
			return "media not found.";
		html = HttpUtil.getResponseString(INDEX_PREFIX + vid, encoding);
		JsonObject jsObj = JsonObject.fromString(html);
		String allot = jsObj.getString("allot");
		jsObj = jsObj.getJsonObject("data");
		StringBuilder sb = new StringBuilder();
		if (jsObj.containsKey("clipsURL")) {
			JsonArray jarr = jsObj.getJsonArray("clipsURL");
			for (int i = 0; i < jarr.size(); i++) {
				String u = jarr.getString(i);
				u = u.replace("data.vod.itc.cn", allot + "/?prot=2&file=");
				String file = jsObj.getJsonArray("su").getString(i);
				u = u + "&new=" + file + "&t=" + Math.random();
				String result = HttpUtil.getResponseString(u);
				String[] tmp0 = result.split("\\|");
				if (!tmp0[4].equals("1"))
					return "i don't know what's this.";
				if (i > 0)
					sb.append("[=]");
				sb.append(tmp0[0] + file.substring(1) + "?key=" + tmp0[3]);
			}
		}
		return sb.toString();
	}

	@Override
	public String getInfo(String userAgent) {
		// TODO Auto-generated method stub
		return null;
	}

}
